<template>
  <div class="page-modal">
    <el-dialog
      v-model="isPageModal"
      :title="isAddRef ? `新增${modelConfigs.title}` : `编辑${modelConfigs.title}`"
      width="35%"
      center
    >
      <el-form :model="pageModalForm" ref="pageModalFormRef">
        <template v-for="item in modelConfigs.fromItems">
          <el-form-item :label="item.label" :label-width="item.width ?? '120px'">
            <template v-if="item.type === 'input'">
              <el-input v-model="pageModalForm[item.prop]" :placeholder="item.placeholder" />
            </template>
            <template v-if="item.type === 'select'">
              <el-select
                v-model="pageModalForm[item.prop]"
                :placeholder="item.placeholder"
                size="large"
              >
                <template v-for="option in item.options">
                  <el-option :label="option.label" :value="option.value" />
                </template>
              </el-select>
            </template>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handelReset">重置</el-button>
          <el-button type="primary" @click="handelSubmit"> 提交 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import useBaseStore from '@/store/main';
import type { FormInstance } from 'element-plus';
import { storeToRefs } from 'pinia';
import { ref } from 'vue';

interface Iprops {
  modelConfigs: {
    title: string;
    fromItems: any[];
    mainMenuName?: string;
  };
  pageName: string;
}

const props = defineProps<Iprops>();

const DpageModalForm: any = {};
props.modelConfigs.fromItems.forEach((item) => {
  DpageModalForm[item.prop] = '';
});

const pageModalForm = ref(DpageModalForm);
const isPageModal = ref(false);
const isAddRef = ref(false);

const pageModalFormRef = ref<FormInstance>();

const baseStore = useBaseStore();
const { sysuserTabs } = storeToRefs(baseStore);

// 重置事件
const handelReset = () => {
  pageModalFormRef.value?.resetFields();
};

// 提交事件
const handelSubmit = () => {
  if (isAddRef) {
    // 添加
    sysuserTabs.value.push(pageModalForm.value);
  } else {
    // 编辑
  }
};

// 编辑和新增事件
const handleChange = (isAdd: boolean, modalInfo?: any) => {
  pageModalForm.value = {};
  if (isAdd) {
    // 添加
  } else {
    // 编辑
    pageModalForm.value = modalInfo;
  }

  isAddRef.value = isAdd;
  isPageModal.value = true;
};

defineExpose({
  handleChange
});
</script>

<style scoped>
.page-modal {
}
</style>
